/*//
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * $("#"+$("#elem_id").val()).attr("desctiption","lalalalala");
 */

$(document).ready(function(){
    $('#object_tree ul li').live('click', function() {
            alert($(this).text() + " :)");
        });
});

(function (){
    $(document).ready(function(){

        $("#tool_add_descriptions").click(function(){
            console.log("Adding description");
            var inputID = $("#elem_id").val();
            var val = prompt("Please insert description.","");
            $("#"+inputID).attr("title",val);
        });

        $("#tool_refresh").click(function(){
            $("#object_tree").empty();
            var root = $("<ul>");
            $("#object_tree").append(root);
            var layers = $("#svgcontent").children("g");
            for(var i =0; i < layers.length; i++){
                var element = layers[i];
                var layersElems = $(element).children();
                var target = $("<ul>");
                console.log(element);
                var li = $("<li>").text(i+1);
                root.append(li);
                li.append(target);
                switchElems(layersElems,target);
            }
        });

        

    });

    function switchElems(elems,target){
        for(var i = 0; i < elems.length; i++){
            var layersElems = elems[i];
            var name = layersElems.tagName;
            if(name == "title"){
            } else if(name.search("^g") > -1){
                var newTarget =$("<ul>");
                target.append( $("<li>").text(layersElems.id).append(newTarget));
                switchElems($("#"+layersElems.id).children(),newTarget);
            } else {
                target.append($("<li>").text(layersElems.id));
            }
        }
    }


})();

function prepareSvg(data){
    data = data.replace(/stroke-width="0.5" stroke="#000000" fill="none" class="fil0 str0"/g,' class="fil0 str0" ');
    data = data.replace(/class="fil0 str0"/g,' stroke-width="0.5" stroke="#000000" fill="none" class="fil0 str0" ');
    return data;
}

function saveHeader(data){
    var startIndex = data.search("<metadata");
    var string_end = "</metadata>"
    var endIndex = data.search(string_end)+length(string_end);
    var metadata = data.substring(startIndex, endIndex);
    jQuery.data(document.body,"metadata",metadata);
}

function readHeader(svg){
    var data = jQuery.data(document.body,"metadata");
    if(data != null){
        var startIndex = svg.search("<metadata");
        var endIndex = svg.search("</metadata>")+11;
        return svg.substring(0,startIndex)+data+svg.substring(endIndex);
    }else{
        return svg;
    }
}